import 'package:dio/dio.dart';
import '../../models/user_model.dart';
import '../../models/api_response.dart';

/// 认证API服务
class AuthApiService {
  final Dio _dio;

  AuthApiService(this._dio);

  /// 用户登录
  Future<ApiResponse<LoginResponse>> login(LoginRequest request) async {
    try {
      // 确保发送的是JSON对象而不是LoginRequest对象
      final response = await _dio.post('/auth/login', data: request.toJson());
      return ApiResponse.fromJson(
        response.data,
        (json) => LoginResponse.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 刷新Token
  Future<ApiResponse<LoginResponse>> refreshToken() async {
    try {
      final response = await _dio.post('/auth/refresh');
      return ApiResponse.fromJson(
        response.data,
        (json) => LoginResponse.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 用户登出
  Future<ApiResponse<void>> logout() async {
    try {
      final response = await _dio.post('/auth/logout');
      return ApiResponse.fromJson(response.data, null);
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 验证Token
  Future<ApiResponse<bool>> validateToken() async {
    try {
      final response = await _dio.get('/auth/validate');
      return ApiResponse.fromJson(
        response.data,
        (json) => json as bool,
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 获取当前用户信息
  Future<ApiResponse<UserInfo>> getCurrentUser() async {
    try {
      final response = await _dio.get('/auth/me');
      return ApiResponse.fromJson(
        response.data,
        (json) => UserInfo.fromJson(json as Map<String, dynamic>),
      );
    } catch (e) {
      throw _handleError(e);
    }
  }

  /// 处理错误
  Exception _handleError(dynamic error) {
    if (error is DioException) {
      if (error.response != null) {
        final statusCode = error.response!.statusCode ?? 0;
        // 从响应体中提取错误消息
        String message = '请求失败';
        if (error.response!.data is Map<String, dynamic>) {
          final data = error.response!.data as Map<String, dynamic>;
          message = data['message'] ?? data['error'] ?? message;
        } else if (error.response!.data is String) {
          message = error.response!.data.toString();
        }

        // 根据状态码返回不同的异常类型
        if (statusCode == 401) {
          return const BusinessException(
            message: '认证失败，请重新登录',
            code: 401,
          );
        } else if (statusCode == 403) {
          return const BusinessException(
            message: '权限不足，无法执行此操作',
            code: 403,
          );
        } else if (statusCode >= 500) {
          return BusinessException(
            message: '服务器内部错误，请稍后重试',
            code: statusCode,
          );
        }

        return NetworkException(
          message: message,
          statusCode: statusCode,
          originalError: error,
        );
      } else {
        return const NetworkException(message: '网络连接失败');
      }
    }
    return NetworkException(
      message: error.toString(),
      originalError: error,
    );
  }
}
